//index.js
import { queryOrderForPage, findOrderByCode } from '../../service/OrderService.js';
import CommonService from '../../service/CommonService';
import wxutil from '../../utils/wxutil.js';
import { identityFilter } from '../../utils/filter.js';
const QQMapWX = require('../../libs/qqmap-wx-jssdk.min.js');
//获取应用实例
const app = getApp()
let qqmapsdk;

Page(identityFilter({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    this.commonService = new CommonService();
    qqmapsdk = new QQMapWX({
      key: 'MNNBZ-KLHKW-AT6RW-R3RV6-FJRJ6-WJBYJ'
    });
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  onShow: function() {
    console.log('123123')
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  getCityList: function(e){
    //console.log('130104'.substr(0, 4)+"00")
    //return;
    const _ = this;
    // 调用接口
    qqmapsdk.getCityList({
      success: function (res) {
        console.log('getCityList',res);
        const result = [];
        //一级城市、二级城市
        /**
        for (let i = 0; i < res.result[0].length; i++){
          const oneCity = res.result[0][i];
          result.push({
            id: oneCity.id,
            name: oneCity.name,
            fullName: oneCity.fullname,
            location: oneCity.location.lat + "," + oneCity.location.lng,
            pinYin: oneCity.pinyin.join('')
          });
          for (let l = oneCity.cidx[0]; l <= oneCity.cidx[1]; l++){
            const twoCity = res.result[1][l];
            result.push({
              id: twoCity.id,
              parentId: oneCity.id,
              name: twoCity.name,
              fullName: twoCity.fullname,
              location: twoCity.location.lat + "," + twoCity.location.lng,
              pinYin: twoCity.pinyin.join('')
            })
          }
        }
         */
        //三级城市
        for (let n = 0; n < res.result[2].length; n++) {
          const threeCity = res.result[2][n];
          result.push({
            id: threeCity.id,
            parentId: threeCity.id.substr(0, 4) + '00',
            name: threeCity.fullname,
            fullName: threeCity.fullname,
            location: threeCity.location.lat + "," + threeCity.location.lng
          })
        }
        console.log(result);
        _.commonService.insertCitys(result);
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },
  getDistrictByCityId: function(e){
    qqmapsdk.getDistrictByCityId({
      id: '110000', // 对应城市ID
      success: function (res) {
        console.log('getDistrictByCityId', res);
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },
  getLocation: function(e){
    wx.getLocation({
      success: function(res){
        // 调用接口
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function (res) {
            console.log(res);
            console.log(res.result.ad_info.city + res.result.ad_info.district);
          },
          fail: function (res) {
            console.log(res);
          },
          complete: function (res) {
            console.log(res);
          }
        });
      }
    })
    
  },
  goFactory: function(e){
    wx.chooseLocation({
      success: function (res){
        console.log(res)
      }
    })
  },
  userInfo: function(){
    // 调用接口
    qqmapsdk.search({
      keyword: '酒店',
      success: function (res) {
        console.log(res);
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },
  phonecallevent: function(){
    const key = 'RESCUE20180712MEGOSKY888rescuems';
    findOrderByCode("JB_1_20180712115401").then(function(result){
      if (result.status == 0 && result.data.result_code == 'SUCCESS'){
        const params = {
          appId: 'wxcadaf904d7fa0bf0',
          timeStamp: Date.parse(new Date()) + '',
          nonceStr: wxutil.createRandom(),
          package: 'prepay_id=' + result.data.prepay_id,
          signType: 'MD5'
        };
        const sign = wxutil.createSign(params, key);
        wx.requestPayment({
          'timeStamp': params.timeStamp,
          'nonceStr': params.nonceStr,
          'package': params.package,
          'signType': params.signType,
          'paySign': sign,
          'success': function (res) {
            if (res.errMsg == 'requestPayment:ok') {
              console.log('支付成功')
            }
          },
          'fail': function (res) {
            console.log('fail')
            console.log(res)
          }
        })
      }
      
    })
    // queryOrderForPage().then(result=>{
    //   console.log(result);
    // });
  },
  toAuth: function(){
    wx.navigateTo({
      url: '/packageUser/pages/auth/auth-rules'
    })
  },
  toOrder: function () {
    wx.navigateTo({
      url: '/packageOrder/pages/order/order-list'
    })
  }
}))
